<?php
/**
 * Created by PhpStorm.
 * User: 小蛮哼哼哼
 * Email: 243194993@qq.com
 * Date: 2021/12/28
 * Time: 20:59
 * motto: 现在的努力是为了小时候吹过的牛逼！
 */

declare(strict_types=1);

namespace app\web\controller;

use app\common\business\Wechat;
use app\common\lib\Show;
use think\Exception;
use think\facade\Log;
use think\facade\Session;

class Login extends WechatBase
{
    public function auth()
    {
        $param = $this->request->param();
        $url = (string)url((string)url('login/doLogin'), $param, false, true);
        $redirectUrl = $this->wechat_app->oauth->scopes(['snsapi_base'])
            ->redirect($url);
        return redirect($redirectUrl);
        exit();
    }

    public function doLogin()
    {
        $param = $this->request->param();
        Log::info(Show::json_encode($param));
        $user = $this->wechat_app->oauth->userFromCode($param['code']);
        Log::info($user->getId());
        $data = [
            "openid" => $user->getId(),
            "type" => 1,
            "nickName" => $user->getName() ?? "",
            "avatarUrl" => $user->getAvatar() ?? "",
        ];
        Log::info(Show::json_encode($data));
        try {
            $wechat = (new Wechat())->addWechat($data);
        } catch (\Exception $e) {
            Log::error($e->getMessage() . " " . $e->getFile() . " " . $e->getLine());
            throw new Exception("发生错误");
        }
        if ($wechat) {
            Session::set(config('key.session_key'), $user->getId());
        }
        $pathinfo = explode('/', $param['pathinfo']);
        if (count($pathinfo) < 3) {
            $url = $param['pathinfo'];
        } else {
            $url = "/" . $param['pathinfo'];
        }
        $array = [];
        if (!empty($param['param'])) {
            $array = $param['param'];
        }
        Log::info("返回连接:" . $url);
        return redirect((string)url("{$url}", $array ?? [], false, false));
    }
}